import httpClient from './AChttpClient'
const mapLogList = (arr) => {
    const result = []
    while (arr.length > 0) {
        const row = arr.pop()
        if (result.find((r) => r.login_name === row.login_name)) {
            const ami = result.find((_r) => (_r.login_name === row.login_name && _r.log_type === row.log_type))
            if (ami) {
                ami.count += 1
            } else {
                result.push(row)
            }
        } else {
            result.push(row)
        }
    }
    return result
}
const uploadUrl = '/site-statistics'
function getIp() {
    httpClient.ajax('get', 'http://pv.sohu.com/cityjson?ie=utf-8', null, {}).then(function (res) {
        console.log(res, '--')
    }).catch(function (err) {
    })
}
function upload(serverUrl, appId, arr = [], ip) {
    const ids = arr.map(r => r.id)
    const _arr = mapLogList(arr)
    const data_arr = _arr.map(r => {
        return {
            appId,
            count: r.count,
            dataType: r.log_type,
            identify: r.login_name
        }
    })
    const header = {
        'Stjh-Real-IP': ip + ''
    }
    httpClient.ajax('post', serverUrl + uploadUrl, data_arr, header).then(function (res) {
        if (res.code === 0) {
            postMessage({ cmd: 'UPLOAD_SUCCESS', ids })
        } else {
        }
    }).catch(function (err) {
    })
}
onmessage = function (event) {
    switch (event.data.cmd) {
        case 'UPLOADLOGLIST':
            const url = event.data.url
            const arr = event.data.log
            const appId = event.data.appId
            const ip = event.data.ip
            upload(url, appId, arr, ip)
            break;
        case 'GETIP':
            getIp()
            break;
        default:
            break;
    }
};